<?php

namespace app\controller\admin;

use think\facade\Db;
use think\facade\View;
use think\facade\Request;

class Category extends Common
{
    public function index($act = null)
    {
        if ($act == 'del') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $ids = input('post.');

            if (!empty($ids)) {
                $r = Db::name('category')->delete($ids['ids']);
                if ($r) {
                    add_log('删除分类，ID：'.implode(',', $ids['ids']), $this->request->user->username);
                    return success(lang('操作成功'), (string) url('admin/category/index'));
                }
            }
            return error(lang('请勾选需要删除的选项'));
        }

        $category = Db::name('category')->field('id,pid,name,o,type')->order('o asc')->select()->toArray();
        $category = categorize_and_sort_hierarchy($category);
        View::assign('category', $category);
        return View::fetch();
    }

    public function add($pid = null)
    {
        $pid = intval($pid);

        $category = Db::name('category')->field('id,pid,name')->order('o asc')->select()->toArray();
        $category = categorize_and_sort_hierarchy($category);
        View::assign('category', $category);
        View::assign('pid', $pid);

        return View::fetch();
    }

    public function edit($id)
    {
        $id = intval($id);
        $category = Db::name('category')->where(['id' => $id])->find();
        if (!$category) {
            return error(lang('参数错误'));
        }
        $categories = Db::name('category')->field('id,pid,name')->order('o asc')->select()->toArray();

        $categories = categorize_and_sort_hierarchy($categories);
        View::assign('category', $category);
        View::assign('categories', $categories);
        View::assign('id', $id);
        return View::fetch();
    }

    public function save($id = null)
    {
        if (!Request::isPost()) {
            return error(lang('参数错误'));
        }
        $data = input('post.');
        if ($data['name'] == '') {
            return error(lang('分类名称不能为空'));
        }
        $id = intval($id);
        $data['o'] = intval($data['o']);
        if ($id) {
            $r = Db::name('category')->where(['id' => $id])->update($data);
            add_log('编辑分类，ID：'.$id, $this->request->user->username);
        } else {
            $r = Db::name('category')->insert($data);
            add_log('新增分类，名称：'.$data['name'], $this->request->user->username);
        }
        if ($r) {
            return success(lang('操作成功'), (string) url('admin/category/index'));
        } else {
            return error(lang('系统错误'));
        }
    }
}
